import { reqlogin, reqGetprofile, reqGetBaseInfo } from '@/api/user'

import { getToken, removeToken, setToken } from '@/utils/auth.js'
import { resetRouter } from '@/router/index'

const state = {
  token: getToken() || '',
  // 用户信息
  userInfo: {}
}
const mutations = {
  // 设置token
  setToken(state, newToken) {
    state.token = newToken
    // 用cookie 永久存储token
    setToken(newToken)
  },

  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  // 清除token
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  // 退出删除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  // 登录获取token
  async login(context, data) {
    const res = await reqlogin(data)
    context.commit('setToken', res.data)

    return res
  },
  async getUserInfo(context) {
    // 获取用户的基本信息
    const res1 = await reqGetprofile()

    // 获取用户的基本资料
    const res2 = await reqGetBaseInfo(res1.data.userId)

    // 合并两次数据
    const res = { ...res1.data, ...res2.data }
    console.log(res)
    context.commit('setUserInfo', res)

    return res // 返回用户的信息
  },
  // 退出登录清除
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
    // 重置路由
    resetRouter()
  }
}
const getters = {

}

export default {
  // 命名空间
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
